<template>
  <view>
    <uv-drop-down
      ref="dropDown"
      :sign="sign"
      :text-active-color="textActiveColor"
      :extra-icon="extraIcon"
      :extra-active-icon="extraActiveIcon"
      :default-value="defaultValue"
      :custom-style="customStyle"
      @click="selectMenu"
    >
      <uv-drop-down-item
        v-for="item in localItems"
        :key="item.name"
        :name="item.name"
        :type="item.type"
        :label="dropItem(item.name).label || item.label"
        :value="dropItem(item.name).value ?? item.value"
      />
    </uv-drop-down>

    <uv-drop-down-popup
      :sign="sign"
      :click-overlay-on-close="clickOverlayOnClose"
      :current-drop-item="currentDropItem"
      @clickItem="clickItem"
      @popupChange="change"
    />
  </view>
</template>

<script setup>
import { ref, computed, reactive, onMounted, watch } from "vue";

// 定义组件的 props，并进行类型和验证
const props = defineProps({
  sign: {
    type: String,
    default: "dropDown_1",
    validator: (value) => typeof value === "string" && value.trim().length > 0,
  },
  textActiveColor: {
    type: String,
    default: "#3c9cff",
  },
  extraIcon: {
    type: Object,
    default: () => ({ name: "arrow-down-fill", color: "#666", size: "26rpx" }),
  },
  extraActiveIcon: {
    type: Object,
    default: () => ({ name: "arrow-up-fill", color: "#3c9cff", size: "26rpx" }),
  },
  customStyle: {
    type: Object,
    default: () => ({ padding: "0 30rpx" }),
  },
  clickOverlayOnClose: {
    type: Boolean,
    default: true,
  },
  items: {
    type: Array,
    default: () => [
      {
        name: "order",
        type: "2",
        label: "综合排序",
        value: "all",
        activeIndex: 0,
        color: "#333",
        activeColor: "#2878ff",
        child: [
          { label: "综合排序", value: "all" },
          { label: "最新发布", value: "new" },
          { label: "低价优先", value: "money" },
        ],
      },
      {
        name: "type",
        type: "2",
        label: "文档格式",
        value: "all",
        activeIndex: 0,
        color: "#333",
        activeColor: "#2878ff",
        child: [
          { label: "全部", value: "all" },
          { label: "PDF", value: "pdf" },
          { label: "WORD", value: "word" },
          { label: "PPT", value: "ppt" },
        ],
      },
      {
        name: "vip_type",
        type: "1",
        label: "VIP文档",
        value: 0,
        activeIndex: 0,
      },
    ],
    validator: (items) =>
      Array.isArray(items) &&
      items.every(
        (item) =>
          item.name &&
          typeof item.name === "string" &&
          item.label &&
          typeof item.label === "string" &&
          "value" in item
      ),
  },
  defaultValue: {
    type: Array,
    default: () => ["all", "all", 0],
    validator: (value) => Array.isArray(value),
  },
});

// 定义组件的 emits 事件
const emit = defineEmits(["update:result", "change"]);

// 响应式状态
const dropDown = ref(null);
const activeName = ref(props.items[0]?.name || "order");
const localItems = reactive(JSON.parse(JSON.stringify(props.items))); // 深度复制 props.items
const result = ref([]);

// 初始化筛选结果
const initResult = () => {
  result.value = localItems
    .map((item) => ({
      name: item.name,
      label: item.label,
      value: item.value,
    }))
    .filter((item) => !props.defaultValue.includes(item.value));
};

// 计算属性：获取指定下拉项的 label 和 value
const dropItem = (name) =>
  computed(() => {
    const resultItem = result.value.find((item) => item.name === name);
    if (resultItem) {
      return { label: resultItem.label, value: resultItem.value };
    }
    const item = localItems.find((i) => i.name === name);
    return item
      ? { label: item.label || "", value: item.value ?? "" }
      : { label: "", value: undefined };
  });

// 计算属性：获取当前激活的下拉项配置
const currentDropItem = computed(() => {
  const item = localItems.find((item) => item.name === activeName.value);
  return item || {};
});

// 处理弹窗状态改变事件
const change = (e) => {
  emit("change", e);
};

// 处理下拉菜单点击事件
const selectMenu = ({ name, active, type }) => {
  if (!name) return;
  activeName.value = name;

  // 处理类型为 "1"（如 VIP 文档）的特殊情况
  if (type === "1") {
    clickItem({
      name,
      label: "VIP文档",
      value: active ? 1 : 0,
    });
    return;
  }

  const find = result.value.find((item) => item.name === name);
  const currentItem = localItems.find((item) => item.name === name);
  if (!currentItem) return;

  // 更新多选项的 activeIndex
  const findIndex =
    find && currentItem.child
      ? currentItem.child.findIndex(
          (item) => item.label === find.label && item.value === find.value
        )
      : 0;
  currentItem.activeIndex = findIndex !== -1 ? findIndex : 0;
};

// 处理下拉菜单子项点击事件
const clickItem = ({ label, value, name }) => {
  if (!name) return;
  const currentItem = localItems.find((item) => item.name === name);
  if (!currentItem) return;

  // 检查是否为默认值
  const isDefaultValue = props.defaultValue.includes(value);

  // 更新本地项的值和标签
  currentItem.value = value;
  // 如果是默认值，标签设为原始默认标签，否则使用选中项的标签
  currentItem.label = isDefaultValue ? currentItem.label : label;

  // 更新或添加筛选结果
  const findIndex = result.value.findIndex((item) => item.name === name);

  if (isDefaultValue) {
    // 如果选中了默认值，则从结果中移除该项
    if (findIndex > -1) {
      result.value.splice(findIndex, 1);
    }
  } else {
    // 如果不是默认值，更新或添加该项
    if (findIndex > -1) {
      result.value[findIndex] = { name, label, value };
    } else {
      result.value.push({ name, label, value });
    }
  }

  // 发射更新后的结果
  emit("update:result", result.value);

  // 刷新下拉菜单
  if (dropDown.value?.init) {
    dropDown.value.init();
  }

  // 在 UniApp 环境中显示筛选结果
  if (typeof uni !== "undefined") {
    uni.showModal({
      content: `筛选的值：${JSON.stringify(result.value)}`,
      showCancel: false,
    });
  }
};

// 生命周期钩子：组件挂载后执行
onMounted(() => {
  initResult();
  if (dropDown.value?.init) {
    dropDown.value.init();
  }

  // 监听页面滚动事件，更新下拉菜单位置
  if (typeof uni !== "undefined") {
    uni.onPageScroll(() => {
      if (dropDown.value?.init) {
        dropDown.value.init();
      }
    });
  }
});

// 监听 props 的 items 和 defaultValue 变化
watch(
  () => [props.items, props.defaultValue],
  ([newItems, newDefaultValue]) => {
    // 验证新传入的 items
    if (
      !Array.isArray(newItems) ||
      !newItems.every(
        (item) =>
          item.name &&
          typeof item.name === "string" &&
          item.label &&
          typeof item.label === "string" &&
          "value" in item
      )
    ) {
      return;
    }

    // 更新本地 items
    Object.assign(localItems, JSON.parse(JSON.stringify(newItems)));

    // 如果当前激活项不存在，重置为第一个
    if (!newItems.some((item) => item.name === activeName.value)) {
      activeName.value = newItems[0]?.name || "order";
    }

    // 更新筛选结果
    result.value = newItems
      .map((item) => ({
        name: item.name,
        label: item.label,
        value: item.value,
      }))
      .filter((item) => !newDefaultValue.includes(item.value));

    // 刷新下拉菜单
    if (dropDown.value?.init) {
      dropDown.value.init();
    }
  },
  { deep: true }
);
</script>
